#include "main.h"

// 要求将所有代码写在本文件内

int ListInitiate(LNode **head)/*初始化*/ {
    *head = (LNode *) malloc(sizeof(LNode));
    (*head)->next = NULL;
    if(!*head)
        return 1;
    else
        return 0;
}

int ListLength(LNode *head) /* 单链表的长度*/{
    LNode *p;
    p = head;
    int i = 0 ;
    while (p->next != NULL) {
        p = p->next;
        i++;
    }
    return i;
}

int ListInsert(LNode *head, int i, DataType x) {
    LNode *p;
    int j;
    p = head;
    j = -1;
    while (p&&j<i-1){
        p = p->next;
        j++;
    }
    if(!p||j>i){
        return 1;
    }
    LNode *s=(LNode *) malloc(sizeof (LNode));
    s->data=x;
    s->next=p->next;
    p->next=s;
    return 0;
}

int ListDelete(LNode *head, int i, DataType *x) {
    LNode *p;
    int j;
    p=head;
    j=-1;
    while (p->next&&j<i-1){
        p=p->next;
        j++;
    }
    if(!(p->next)||j>i){
        return 1;
    }
    LNode *s=p->next;
    p->next=s->next;
    *x = s->data;
    free(s);
    return 0;
}

int ListGet(LNode *head, int i, DataType *x) {
    LNode *p;
    int j;
    p=head;
    j=-1;
    while (p&&j<i){
        p = p->next;j++;
    }
    if(!p||j>i)
        return 1;
    *x = p->data;
    return 0;
}

int Destroy(LNode **head)
{
    LNode *p,*s;
    p = *head;
    while (p!=NULL){
        s = p;
        p = p->next;
        free(s);
    }
    *head = NULL;
    if(*head==NULL)
        return 0;
    else
        return 1;
}

void main(void) {
    LNode *head;
    int i , x;
    ListInitiate(&head);/*初始化*/
    for(i = 0; i < 10; i++) {
        if(ListInsert(head, i, i+1) == 1) /*插入10个数据元素*/
        {
            printf("错误\n");
            return;
        }
    }

    if(ListDelete(head, 4, &x) == 1) { /*删除数据元素5*/
        printf("错误\n");
        return;
    }
    printf("%d\n", ListLength(head));

    for(i = 0; i < ListLength(head); i++) {
        if(ListGet(head, i, &x) == 1) /*取元素*/
        {
            printf("错误\n");
            return;
        }
        else printf("%d     ", x);/*显示数据元素*/
    }

    Destroy(&head);

}